package com.runlooker.runer.dao;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.runlooker.runer.db.RunerDBOpenHelper;
import com.runlooker.runer.db.RunerTableSql;
import com.runlooker.runer.entity.ChatMsgEntity;

public class ChatMsgDao {
	private String mTable = RunerTableSql.MESSAGE_ENTRY_TABLE;

	private RunerDBOpenHelper mRunerDBOpenHelper;

	public ChatMsgDao(Context context) {
		mRunerDBOpenHelper = new RunerDBOpenHelper(context);
	}

	// /**
	// * 判断联系人信息是否存在数据库中
	// *
	// * @param account
	// * @return
	// */
	// public boolean IsExists(String id) {
	// SQLiteDatabase db = mRunerDBOpenHelper.getReadableDatabase();
	// boolean flag = IsExists(id, db);
	// // db.close();
	// return flag;
	// }

	private boolean IsExists(String id, SQLiteDatabase db) {
		boolean flag = false;
		if (id == null) {
			return flag;
		}
		Cursor cursor = db.query(mTable, null, "packetId = ? ",
				new String[] { id }, null, null, null);
		if (cursor != null && cursor.getCount() > 0) {
			flag = true;
		} else {
			flag = false;
		}
		// cursor.close();
		return flag;
	}

	/**
	 * 
	 * 清空表
	 * 
	 * @Title: clearTable
	 * @description: 方法描述
	 */
	public synchronized void clearTable() {
		SQLiteDatabase db = mRunerDBOpenHelper.getReadableDatabase();
		StringBuffer updateSql = new StringBuffer("DELETE FROM " + mTable);
		db.execSQL(updateSql.toString());
		// db.close();
	}

	public synchronized void deleInfoByAccount(String account) {
		SQLiteDatabase db = mRunerDBOpenHelper.getReadableDatabase();
		String[] args = { account };
		db.delete(mTable, "chatAccount = ? ", args);
		// db.close();
	}

	public synchronized List<ChatMsgEntity> getEntitiesByLimit(String account,
			int page, int pageSize) {
		SQLiteDatabase db = mRunerDBOpenHelper.getReadableDatabase();
		LinkedList<ChatMsgEntity> list = new LinkedList<ChatMsgEntity>();
		Cursor cursor = db.query(
				mTable,
				null,
				"chatAccount = ? ",
				new String[] { account + "" },
				null,
				null,
				"id DESC",
				String.valueOf(page * pageSize) + ","
						+ String.valueOf(pageSize));
		cursor.moveToLast();
		if (cursor != null && cursor.getCount() > 0) {
			do {
				ChatMsgEntity msg = new ChatMsgEntity();
				msg.setPacketId(cursor.getString(cursor
						.getColumnIndex("packetId")));
				msg.setChatAccount(cursor.getString(cursor
						.getColumnIndex("chatAccount")));
				msg.setIsReaded(cursor.getInt(cursor.getColumnIndex("isReaded")));
				msg.setIsSended(cursor.getInt(cursor.getColumnIndex("isSended")));
				msg.setMessage(cursor.getString(cursor
						.getColumnIndex("message")));
				msg.setMsgType(cursor.getInt(cursor.getColumnIndex("msgType")));
				msg.setMsgSourse(cursor.getInt(cursor
						.getColumnIndex("msgSourse")));
				msg.setDescription(cursor.getString(cursor
						.getColumnIndex("description")));
				msg.setFileName(cursor.getString(cursor
						.getColumnIndex("fileName")));
				msg.setVoicePlayStatus(cursor.getInt(cursor
						.getColumnIndex("voicePlayStatus")));
				msg.setPath(cursor.getString(cursor.getColumnIndex("path")));
				msg.setGroupId(cursor.getInt(cursor.getColumnIndex("groupId")));
				msg.setChatType(cursor.getInt(cursor.getColumnIndex("chatType")));
				msg.setTime(cursor.getString(cursor.getColumnIndex("time")));
				list.add(msg);
			} while (cursor.moveToPrevious());
		}
		cursor.close();
		// db.close();
		return list;
	}

	/**
	 * 
	 * 
	 * @param account
	 * @return List<ChatMsgEntity> ，如果没有数据，则该list的size为0
	 */
	public synchronized List<ChatMsgEntity> getChatMsgEntities(String account) {
		SQLiteDatabase db = mRunerDBOpenHelper.getReadableDatabase();
		List<ChatMsgEntity> list = new ArrayList<ChatMsgEntity>();
		String sql = "SELECT * FROM " + mTable + " WHERE chatAccount = " + "'"
				+ account + "'";
		Cursor cursor = db.rawQuery(sql, null);
		if (cursor != null && cursor.getCount() > 0) {
			while (cursor.moveToNext()) {
				ChatMsgEntity msg = new ChatMsgEntity();
				msg.setPacketId(cursor.getString(cursor
						.getColumnIndex("packetId")));
				msg.setChatAccount(cursor.getString(cursor
						.getColumnIndex("chatAccount")));
				msg.setIsReaded(cursor.getInt(cursor.getColumnIndex("isReaded")));
				msg.setIsSended(cursor.getInt(cursor.getColumnIndex("isSended")));
				msg.setMessage(cursor.getString(cursor
						.getColumnIndex("message")));
				msg.setMsgType(cursor.getInt(cursor.getColumnIndex("msgType")));
				msg.setMsgSourse(cursor.getInt(cursor
						.getColumnIndex("msgSourse")));
				msg.setDescription(cursor.getString(cursor
						.getColumnIndex("description")));
				msg.setFileName(cursor.getString(cursor
						.getColumnIndex("fileName")));
				msg.setVoicePlayStatus(cursor.getInt(cursor
						.getColumnIndex("voicePlayStatus")));
				msg.setPath(cursor.getString(cursor.getColumnIndex("path")));
				msg.setGroupId(cursor.getInt(cursor.getColumnIndex("groupId")));
				msg.setChatType(cursor.getInt(cursor.getColumnIndex("chatType")));
				msg.setTime(cursor.getString(cursor.getColumnIndex("time")));
				list.add(msg);
			}
		}
		cursor.close();
		// db.close();
		return list;
	}

	/**
	 * 
	 * 更新指定id消息的发送状态
	 * 
	 * @param status
	 */
	public synchronized void updateMsgSendStatus(String id, int status) {
		SQLiteDatabase db = mRunerDBOpenHelper.getReadableDatabase();
		if (!IsExists(id, db)) {
			return;
		}
		ContentValues values = new ContentValues();
		values.put("isSended", status);
		String[] args = { id + "" };
		db.update(mTable, values, "packetId = ?", args);
		// db.close();
	}

	/**
	 * 
	 * 更新消息已读和未读状态
	 * 
	 * @param id
	 * @param status
	 */
	public synchronized void updateMsgReadStatus(String id, int status) {
		SQLiteDatabase db = mRunerDBOpenHelper.getReadableDatabase();
		if (!IsExists(id, db)) {
			return;
		}
		ContentValues values = new ContentValues();
		values.put("isReaded", status);
		String[] args = { id + "" };
		db.update(mTable, values, "packetId = ?", args);
		// db.close();
	}

	private void updateMsg(ChatMsgEntity msg, SQLiteDatabase db) {
		if (msg == null || !IsExists(msg.getPacketId(), db)) {
			return;
		}
		ContentValues values = new ContentValues();
		values.put("chatAccount", msg.getChatAccount());
		values.put("time", msg.getTime());
		values.put("message", msg.getMessage());
		values.put("isReaded", msg.getIsReaded());
		values.put("isSended", msg.getIsSended());
		values.put("description", msg.getDescription());
		values.put("msgType", msg.getMsgType());
		values.put("groupId", msg.getGroupId());
		values.put("fileName", msg.getFileName());
		values.put("path", msg.getPath());
		values.put("chatType", msg.getChatType());
		values.put("msgSourse", msg.getMsgSourse());
		values.put("voicePlayStatus", msg.getVoicePlayStatus());
		String[] args = { msg.getPacketId() };
		db.update(mTable, values, "packetId = ?", args);
	}

	public synchronized void saveMsg(ChatMsgEntity msg) {
		SQLiteDatabase db = mRunerDBOpenHelper.getReadableDatabase();
		saveMsg(msg, db);
	}

	public synchronized void saveOrUpdate(ChatMsgEntity msg) {
		SQLiteDatabase db = mRunerDBOpenHelper.getReadableDatabase();
		if (IsExists(msg.getPacketId(), db)) {
			updateMsg(msg, db);
		} else {
			saveMsg(msg, db);
		}
	}

	/**
	 * 保存信息
	 * 
	 * @param msg
	 */
	private void saveMsg(ChatMsgEntity msg, SQLiteDatabase db) {
		if (msg == null || IsExists(msg.getPacketId(), db)) {
			return;
		}
		ContentValues values = new ContentValues();
		values.put("chatAccount", msg.getChatAccount());
		values.put("time", msg.getTime());
		values.put("message", msg.getMessage());
		values.put("isReaded", msg.getIsReaded());
		values.put("isSended", msg.getIsSended());
		values.put("description", msg.getDescription());
		values.put("msgType", msg.getMsgType());
		values.put("groupId", msg.getGroupId());
		values.put("fileName", msg.getFileName());
		values.put("path", msg.getPath());
		values.put("chatType", msg.getChatType());
		values.put("msgSourse", msg.getMsgSourse());
		values.put("voicePlayStatus", msg.getVoicePlayStatus());
		values.put("packetId", msg.getPacketId());
		db.insert(mTable, null, values);
		// db.close();
	}

}
